from pydantic import BaseModel, Field, validator
from datetime import datetime
from typing import Optional, Dict, Any, List
import re
from enum import Enum


# 枚举定义
class DBCenterEnum(str, Enum):
    Bcenter = "Bcenter"
    Omscenter = "Omscenter"
    Listingcenter = "Listingcenter"
    Icenter = "Icenter"
    Pcenter = "Pcenter"
    Gcenter = "Gcenter"


class AlertLevelEnum(str, Enum):
    NORMAL = "NORMAL"
    URGENT = "URGENT"
    CRITICAL = "CRITICAL"


class OperatorEnum(str, Enum):
    gt = ">"
    lt = "<"
    eq = "="
    gte = ">="
    lte = "<="
    ne = "!="


class StandardTypeEnum(str, Enum):
    SQL = "SQL"
    FIXED = "FIXED"


class ScheduleTypeEnum(str, Enum):
    interval = "interval"
    cron = "cron"


# 预警规则基础模型
class AlertRuleBase(BaseModel):
    rule_name: str = Field(..., max_length=100)
    origin_db: DBCenterEnum = Field(DBCenterEnum.Bcenter, description="检测的DB")
    query_sql: str
    operator: OperatorEnum
    standard_type: StandardTypeEnum
    dest_db: DBCenterEnum = Field(DBCenterEnum.Bcenter, description="标准值的DB")
    standard_value: str
    alert_level: AlertLevelEnum = Field(AlertLevelEnum.NORMAL)
    owner: str
    is_active: bool = True
    task_group: str = Field('hourly', description="所属任务组")
    frequency: str = Field('1h', description="执行频率: 10m(10分钟), 1h(1小时), 1d(1天), daily:01:00(每天1点)")
    timezone: str = Field('UTC', description="时区设置")
    skip_weekends: bool = Field(False, description="是否跳过周末")
    skip_holidays: bool = Field(False, description="是否跳过节假日")

    @validator('frequency')
    def validate_frequency(cls, v):
        """验证频率格式"""
        # 验证简单频率格式
        if re.match(r'^\d+[mhd]$', v):
            return v

        # 验证固定时间格式
        if v.startswith('daily:'):
            time_part = v[6:]
            if re.match(r'^\d{1,2}:\d{2}$', time_part):
                try:
                    hour, minute = map(int, time_part.split(':'))
                    if 0 <= hour <= 23 and 0 <= minute <= 59:
                        return v
                except ValueError:
                    pass

        raise ValueError('无效的频率格式。格式应为: 10m, 1h, 1d 或 daily:HH:MM')


# 预警规则创建模型
class AlertRuleCreate(AlertRuleBase):
    pass


# 预警规则更新模型
class AlertRuleUpdate(AlertRuleBase):
    pass


# 预警规则响应模型
class AlertRuleResponse(AlertRuleBase):
    id: int
    created_at: datetime
    updated_at: datetime
    last_trigger_time: Optional[datetime] = None


# 预警历史响应模型
class AlertHistoryResponse(BaseModel):
    id: int
    rule_id: int
    rule_name: str
    actual_value: str
    operator: Optional[str] = None
    standard_value: str
    notification_flag: bool
    trigger_time: datetime
    notification_sent: bool
    notification_method: Optional[str] = None


# 任务组基础模型
class AlertTaskGroupBase(BaseModel):
    group_name: str = Field(..., max_length=50)
    description: Optional[str] = None
    schedule_type: ScheduleTypeEnum = Field(ScheduleTypeEnum.interval)
    schedule_value: Dict[str, Any]
    is_active: bool = True

    @validator('schedule_value')
    def validate_schedule_value(cls, v):
        """验证调度配置值"""
        if not isinstance(v, dict):
            raise ValueError('schedule_value 必须是字典类型')
        return v


# 任务组创建模型
class AlertTaskGroupCreate(AlertTaskGroupBase):
    pass


# 任务组响应模型
class AlertTaskGroupResponse(AlertTaskGroupBase):
    id: int
    last_run_time: Optional[datetime] = None
    created_at: datetime


# 任务组列表响应模型
class TaskGroupListResponse(BaseModel):
    items: List[AlertTaskGroupResponse]
    total: int


# 规则列表响应模型
class RuleListResponse(BaseModel):
    items: List[AlertRuleResponse]
    total: int


# 历史记录列表响应模型
class HistoryListResponse(BaseModel):
    items: List[AlertHistoryResponse]
    total: int


# 手动触发响应模型
class TriggerResponse(BaseModel):
    status: str
    rule_id: int
    rule_name: str
    actual_value: Any
    notification_sent: Optional[bool] = None
    notification_method: Optional[str] = None


# 任务组执行响应模型
class TaskGroupRunResponse(BaseModel):
    message: str